/**
 * 
 */
package org.joy.nlp;

/**
 * @author  LvSaiHui {gurnfe@163.com}
 * @version  1.0
 * <br>Copyright (C), 2007-2008, ZJUT
 * <br>This program is protected by copyright laws.
 * <br>Program Name: HLWordSpliterThreadLocal.java
 * <br>Date: 2009-3-5
 * <br>Description: 
 */
public class HLWordSpliterThreadLocal implements WordSpliter{

   // private static HLS h = null;
	ThreadLocal threadLocal = new ThreadLocal();
    private final static Object waiter = new Object();

    public HLWordSpliterThreadLocal() {
        synchronized (waiter) {
            /*if (h == null) {
                h = new HLS();
                //h.HLSplitInit("./dicts/");
                h.HLSplitInit("F:/joyhtml/joyhtml-0.2.2/dicts/");
            }*/
        	if(threadLocal.get()==null){
        		threadLocal.set(new HLS());
        		((HLS)threadLocal.get()).HLSplitInit("F:/joyhtml/joyhtml-0.2.2/dicts/");
        		
        	}
        }
    }

    public void close() {
        synchronized (waiter) {
            /*if (h != null) {
                h.HLFreeSplit();
                h = null;
            }*/
        	if(threadLocal.get()!=null){
        		
        		HLS h= (HLS)threadLocal.get();
        		h.HLFreeSplit();
        		threadLocal.set(null);
        	}
        }


    }

    public String[] split(String text) {
        return split(text, false).split(" ");
    }

    public String split(String text, boolean isTagged) {
        synchronized (waiter) {
            if (threadLocal.get() == null) {
                System.out.println("分词系统已经关闭！");
                return null;
            } else {
            	//System.out.println(threadLocal.get().toString());
            	HLS h=(HLS)threadLocal.get();
                return h.HLS_ParagraphProcess(text, isTagged ? 1 : 0);
            }
        }


    }

    public Word[] splitToWords(String text) {
        String[] s = split(text, true).replaceAll("\\s+/W", "").split(" ");
        Word[] words = new Word[s.length];
        for (int i = 0; i < s.length; i++) {
            String wordText = s[i].split("/")[0];
           // String wordTag = s[i].split("/")[1];
            String wordTag = s[i].split("/")[0];

            words[i] = new Word(wordText, wordTag);
        }

        return words;
    }

    public static void main(String[] args) {
    	HLWordSpliterThreadLocal h = new HLWordSpliterThreadLocal();
        System.out.println(h.split("美国中央情报局是   特务间谍机构。", true));

        for (Word w : h.splitToWords("世界十大色狼之柳松大侠！")) {
            System.out.print(w.getText() + "/" + w.getTag() + " ");
        }
        System.out.println("");


        System.out.println(h.split("我们在领导的帮助下，实现了这个功能。", true));
        h.close();
        System.out.println(h.split("中国人  是好人", false));
    }


}
